package com.item.manager.serialize;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

import static java.util.Arrays.asList;

/**
 * Loads templates from file.
 *
 * Created by Alexey on 3/2/2015.
 */
public class TemplateLoader implements Supplier<List<TemplateAdaptor>> {
    private final String source;

    public TemplateLoader(String source) {
        this.source = source;
    }

    public static Supplier<List<TemplateAdaptor>> classPath(String name) {
        return  () -> asList(toYml(ClassLoader.getSystemClassLoader().getResourceAsStream(name)));
    }

    public static Supplier<List<TemplateAdaptor>> fileName(String name) {
        return () -> {
            try {
                return asList(toYml(new FileInputStream(new File(name))));
            } catch (Exception e) {
                throw new RuntimeException("File not found", e);
            }
        };
    }

    public List<TemplateAdaptor> get() {
        return asList(toYml(ClassLoader.getSystemClassLoader().getResourceAsStream(source)));
    }

    public static Consumer<TemplateAdaptor[]> fileConsumer(String filePath) {
        return a -> {
            try {

                ymlMapper().writeValue(new File(filePath), a);
            } catch (IOException e) {
                throw new RuntimeException("Exception during parsing", e);
            }
        };
    }

    private static TemplateAdaptor[] toYml(InputStream is) {
        ObjectMapper mapper = ymlMapper();
        try {
            return mapper.readValue(is, TemplateAdaptor[].class);
        } catch (IOException e) {
            throw new RuntimeException("Exception during parsing", e);
        }
    }

    private static ObjectMapper ymlMapper() {
        YAMLFactory jf = new YAMLFactory();
        ObjectMapper mapper = new ObjectMapper(jf);
        return mapper;
    }
}
